/*
 * @Author: YTian
 * @Date: 2023-05-12 15:45:45
 * @LastEditTime: 2023-05-19 15:18:40
 * @Description: api文件
 * @FilePath: \pcsong\src\global\api.ts
 */
// ========= 导入axios ========= //
import axios from 'axios'

const song__api: string = 'http://8.130.23.219:3000'

// & 推荐歌单
export type personalized_type = {
	// & id
	id: string
	// & 名称
	name: string
	// & 封面
	cover: string
}

/**
 * 获取推荐歌单。返回由id, 名称， 封面链接组成了对象数据
 *
 * @description: 获取推荐歌单
 * @param {*} limit?: number # 控制获取多少个歌单
 * @return {*}
 */

const api_personalized = async (
	limit: number = 30
): Promise<personalized_type[]> => {
	const res = await axios(`${song__api}/personalized?limit=${limit}`)

	return res.data.result.map(
		(item: { id: string; name: string; picUrl: string }) => {
			return { id: item.id, name: item.name, cover: item.picUrl }
		}
	)
}

type song__list__detail_type = {
	// # 歌单名称
	name: string
	// # 歌单封面
	cover: string
	// # 描述
	description: string
	// # 歌曲
	song__ids: string[]
}

/**
 * @description: 获取歌单详情
 * @param {string} id
 * @return {*}
 */
const api_song__list__detail = async (
	id: string
): Promise<song__list__detail_type> => {
	const res = await axios(`${song__api}/playlist/detail?id=${id}`)

	return {
		name: res.data.playlist.name,
		cover: res.data.playlist.coverImgUrl,
		description: res.data.playlist.description,
		song__ids: res.data.playlist.trackIds.map(
			(item: { id: string }) => item.id + ''
		)
	}
}

export { api_song__list__detail, api_personalized }

// ========= 歌曲部分 ========= //

// & 歌曲类型
export type Song = {
	id: string
	// & 歌曲名称
	song__name: string
	// & 歌曲作者
	artist: string
	// & 封面
	cover: string
	// & 专辑
	album: string
}

type ar_temp = {
	name: string
	[key: string]: any
}

/**
 * @description: 处理函数, 因为会在多个地方掉用所以抽了出来
 * @param {any} item
 * @return {*}
 */
const details = (item: any): Song => {
	return {
		id: item.id,
		song__name: item.name,
		cover: item.al.picUrl,
		artist: (item.ar as ar_temp[]).map((item) => item.name).join('&'),
		album: item.al.name
	}
}

/**
 * @description: 传入id,或id的集合返回歌曲详情
 * @param {string|string[]} ids
 * @return {*}
 */
const song__details = async (ids: string | string[]): Promise<Song[]> => {
	const res = await axios(
		`${song__api}/song/detail?ids=${
			Array.isArray(ids) ? ids.join(',') : ids
		}`
	)

	return res.data.songs.map((item: any) => details(item))
}

/**
 * @description: 传入id, 获取歌曲播放链接
 * @param {string} id
 * @return {*}
 */
const link_get = async (id: string): Promise<string> => {
	const res = await axios(`${song__api}/song/url?id=${id}`)
	return res.data.data[0].url
}

export { song__details, link_get }

// ========= 歌词获取和处理 ========= //

/**
 * @description: 将分秒变成秒
 * @param {string} time
 * @return {*}
 */
const time_to_sec = (time: string): number => {
	let sec_new = 0

	const min: number = +time.split(':')[0]
	const sec: number = +time.split(':')[1]

	sec_new = min * 60 + sec
	return sec_new
}

/**
 * @description: 传入id获取处理好的歌词
 * @param {string} id
 * @return {*}
 */
const deal__with = async (id: string): Promise<{ [key: string]: string }> => {
	const res = await axios(`${song__api}/lyric?id=${id}`)

	let arr = res.data.lrc.lyric.trim().split('\n')

	let temp_return = {}

	arr.forEach((element: string) => {
		const place__index = element.indexOf(']')

		temp_return[time_to_sec(element.slice(1, place__index)).toFixed(3)] =
			element.slice(place__index + 1).trim()
	})

	return temp_return
}

export { deal__with }

// ========= 搜索 ========= //

/**
 * @description: 搜索的处理函数
 * @return {*}
 */
const dispose_search: { [key: string]: Function } = {
	'1': async (res: any): Promise<Song[]> => {
		const ids = res.data.result.songs.map(
			(item: { id: string }) => item.id + ''
		)
		const data: Song[] = await song__details(ids)
		return data
	},
	'100': (res: any) => {
		return res.data.result.artists.map(
			(item: { name: string; id: string; picUrl: string }) => {
				return {
					id: item.id + '',
					name: item.name + '',
					cover: item.picUrl + ''
				}
			}
		)
	},
	'1000': async (res: any): Promise<personalized_type[]> => {
		return res.data.result.playlists.map(
			(item: { id: string; name: string; coverImgUrl: string }) => {
				return {
					id: item.id + '',
					name: item.name + '',
					cover: item.coverImgUrl + ''
				}
			}
		)
	}
}

/**
 * @description: 搜索
 * @return {*}
 */
const api_search = async (
	keywords: string,
	type: 1 | 100 | 1000 = 1
): Promise<Song[] | personalized_type[]> => {
	const res = await axios(
		`${song__api}/search?keywords=${keywords}&type=${type}`
	)

	return dispose_search[type + ''](res)
}

export { api_search }

// ========= 获取歌手详情 ========= //
export type Artists_type = {
	// & 歌手的描述
	details: {
		// # 名称
		name: string
		// # 封面
		cover: string
		// # 描述
		description: string
	}
	links: Song[]
}

/**
 * @description: 获取歌手详情
 * @param {string} id
 * @return {*}
 */
const api_artists = async (id: string): Promise<Artists_type> => {
	const res = await axios(`${song__api}/artists?id=${id}`)

	const end: Artists_type = {
		details: {
			name: res.data.artist.name + '',
			cover: res.data.artist.picUrl + '',
			description: res.data.artist.briefDesc + ''
		},
		links: res.data.hotSongs.map((item: any): Song => details(item))
	}

	return end
}

export { api_artists }

// ========= 下载 ========= //
const download = (id: string, name: string): void => {
	axios(`http://8.130.23.219:3000/song/download/url?id=${id}&br=320000`).then(
		(res) => {
			axios({
				url: res.data.data.url,
				method: 'GET',
				responseType: 'blob'
			}).then((response) => {
				const url = window.URL.createObjectURL(
					new Blob([response.data])
				)
				const link = document.createElement('a')
				link.href = url
				link.setAttribute('download', `${name}.mp3`)
				document.body.appendChild(link)
				link.click()

				// 下载完成后删除文件
				URL.revokeObjectURL(url) // 释放对象URL
				document.body.removeChild(link) // 从文档中删除链接元素
			})
		}
	)
}

export { download }
